/*
 * 5.3
 * Given an integer, print the next smallest and next largest number that have the same
 * number of 1 bits in their binary representation.
 */
#include <stdio.h>

// XXX: was totally misunderstood!!!
int next_smallest(int i)
{
    /* set first bit */
    int a = 30;
    while (a >= 0 && ((1 << a) & i) == 0) {
        a--;
    }
    i |= 1 << (a + 1);
    /* set second bit */
    i &= ~(1 << a);
    /* set remaining bits */
    int r = i & ((1 << a) - 1);
    int n = 0;
    while (r) {
        r &= (r-1);
        n++;
    }
    i &= ~((1 << a) - 1);
    i |= (1 << n) - 1;
    return i;
}

// XXX: totally misunderstood!!!
int next_largest(int i)
{
    /* set first bit */
    int a = 30;
    while (a >= 0 && ((1 << a) & i) == 0) {
        a--;
    }
    i &= ~(1 << a);
    /* set second bit */
    i |= 1 << (a - 1);
    /* set remaining bits */
    int r = i & ((1 << a) - 1);
    int n = 0;
    while (r) {
        r &= (r-1);
        n++;
    }
    i &= ~((1 << (a-1)) - 1);
    int r2 = (1 << n) - 1;
    i |= r2 << (a - n);
    return i;
}

int main()
{
    int a = next_smallest(28);
    int b = next_largest(35);
    printf("a=%d,b=%d.\n", a, b);
    return 0;
}
